package com.sam.stockvalue.service.impl;

import com.sam.stockvalue.model.TStockConfig;
import com.sam.stockvalue.service.StockSpiderService;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @description:
 * @author:
 */
@Service
public class StockSpiderServiceImpl implements StockSpiderService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    private ThreadLocal<WebDriver> threadLocal = new ThreadLocal<>();

    @Value("${seleniumDriverPath}")
    String driverPath;

    @Override
    public void doSpiderStock(TStockConfig stockConfig) {

        this.seleniumProcess(stockConfig);
    }

    @Override
    public void clearThreadLocal() {
        if(threadLocal.get() != null) {
            threadLocal.get().close();
            threadLocal.remove();
        }
    }

    /**
     * selenium可以爬取ajax异步请求的数据
     * @param stockConfig
     */
    private void seleniumProcess(TStockConfig stockConfig) {

        String uri = "http://quote.eastmoney.com/sh" + stockConfig.getCode() + ".html";
//        String uri = "https://finance.sina.com.cn/realstock/company/sh" + stockConfig.getCode() + "/nc.shtml";

        WebDriver webDriver = this.fillWebDriver();
        webDriver.get(uri);
        WebElement webElements = webDriver.findElement(By.id("price9"));
        String stockPrice = webElements.getText();
        logger.info("{}最新股价为 >>> {}", stockConfig.getCode(), stockPrice);
        stockConfig.setCurPrice(new BigDecimal(stockPrice));
//        webDriver.close();
    }

    private WebDriver fillWebDriver() {
        if(threadLocal.get() != null) {
            return threadLocal.get();
        }
        // 设置 chromedirver 的存放位置
        System.getProperties().setProperty("webdriver.chrome.driver", driverPath);
        // 设置无头浏览器，这样就不会弹出浏览器窗口
        ChromeOptions chromeOptions = new ChromeOptions();
        // 禁用沙箱
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--disable-dev-shm-usage");
        chromeOptions.addArguments("--headless");

        WebDriver webDriver = new ChromeDriver(chromeOptions);
        threadLocal.set(webDriver);
        return webDriver;
    }
}
